//
//  NNAlertViewController.swift
//  CommonTool
//
//  Created by tenroadshow on 24.1.22.
//

import UIKit

/// Alert控制器
class NNAlertViewController: UIViewController {

    // Private
    private lazy var transitionDelegate = NNAlertTransition(dimmingViewColor: UIColor(white: 0, alpha: 0.2))
    private lazy var contentView: UIView = UIView()
        
    public var contentCornerRadius: CGFloat = 5.0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        contentView.backgroundColor = .white
        view.addSubview(contentView)
        contentView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    // public
    public func show(animated: Bool = true) {
        let topViewController = UIViewController.topViewController()
        topViewController?.present(self, animated: animated, completion: nil)
    }
    
    public func hide(animated: Bool = true, completion: (() -> Void)? = nil) {
        dismiss(animated: animated, completion: completion)
    }
    

    // 设置倒角
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let cornerRadiusPath = UIBezierPath(roundedRect: contentView.bounds,
                                            byRoundingCorners: .allCorners,
                     cornerRadii: CGSize(width: contentCornerRadius, height: contentCornerRadius))
        let shapLayer = CAShapeLayer()
        shapLayer.path = cornerRadiusPath.cgPath
        contentView.layer.mask = shapLayer
    }
}


extension NNAlertViewController {
        
    /// 显示自定义视图
    /// - Parameter customView: 自定义视图
    /// - Returns: Alert控制器
    public static func showCustomAlert(customView: UIView) -> NNAlertViewController {
        
        let controller = NNAlertViewController()
        controller.modalPresentationStyle = .custom
        controller.transitioningDelegate = controller.transitionDelegate

        controller.contentView.addSubview(customView)
        customView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
            make.width.equalTo(UIScreen.main.bounds.size.width * 0.618)
        }
        controller.show()
        return controller
    }
    
    
    /// 显示title/message 弹窗
    /// - Parameters:
    ///   - title: 标题
    ///   - message: 内容
    ///   - config: 配置
    ///   - actionHandle: 事件回调
    public static func show(title: String? = nil,
                            message: String? = nil,
                            config: ((inout NNMessageAlertStyle) -> ())? = nil,
                            actionHandle: @escaping ((_ isOk: Bool) -> ())) {
        var style: NNMessageAlertStyle = NNMessageAlertStyle()
        config?(&style)
        style.title = title
        style.message = message
        
        let messageView = NNMessageAlertView(style: style)
        messageView.message = message
        let alertController = showCustomAlert(customView: messageView)
        
        messageView.btnActionHandle = {  shouldOperation in
            alertController.hide(animated: true) {
                actionHandle(shouldOperation)
            }
        }
    }
}



struct NNMessageAlertStyle {
    
    // Title
    var title: String? = nil
    var titleNumberOfLines: Int = 1
    var titleFont: UIFont = UIFont.boldSystemFont(ofSize: 15)
    var titleContentInset = UIEdgeInsets(top: 20, left: 20, bottom: 10, right: 20)

    // Message
    var message: String? = nil
    var messageNumberOfLines: Int = 0
    var messageFont: UIFont = UIFont.systemFont(ofSize: 15)
    // 如果有标题，内部 messageContentInset.top值 无效；如果需要调整标题与内容间距，请调节titleContentInset.bottom的值；默认为10
    var messageContentInset = UIEdgeInsets(top: 20, left: 20, bottom: 15, right: 20)

    // 按钮
    var buttonHeight: CGFloat = 40.0
    var buttonFont: UIFont = UIFont.systemFont(ofSize: 15)
    var cancelBtnColor: UIColor = UIColor.black
    var cancelBtnTitle: String? = "Cancel"
    
    var okBtnColor: UIColor = UIColor.black
    var okBtnTitle: String? = "OK"

    // 是否是两个按钮
    var isDoubleBtn: Bool = false
    // 当两个按钮时，取消按钮是否在右边
    var isCancelRight: Bool = false
}


class NNMessageAlertView: UIView {
    private lazy var titleContainer: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 15)
        label.textAlignment = .center
        return label
    }()

    
    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15)
        label.textAlignment = .center
        return label
    }()
    
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("cancel", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.backgroundColor = UIColor.white
        btn.addTarget(self,
                      action: #selector(cancelBtnAction(sender:)),
                      for: .touchUpInside)
        return btn
    }()
    
    private lazy var okBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("ok", for: .normal)
        btn.setTitleColor(UIColor.black, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        btn.backgroundColor = UIColor.white
        
        btn.addTarget(self,
                      action: #selector(okBtnAction(sender:)),
                      for: .touchUpInside)
        return btn
    }()
    
    
    private var style: NNMessageAlertStyle = NNMessageAlertStyle()
    public var message: String? {
        didSet {
            messageLabel.text = message
        }
    }
    
    public var btnActionHandle: ((_ shouldOperation: Bool) -> ())?
    
    convenience init(style: NNMessageAlertStyle) {
        self.init()
        self.style = style
        setupUI()
    }
    
    private func setupUI() {
        backgroundColor = UIColor(white: 0, alpha: 0.1)
        
        var lastView: UIView?
        // 1. 添加标题
        if let title = style.title, !title.isEmpty {
            titleLabel.font = style.titleFont
            titleLabel.numberOfLines = style.titleNumberOfLines

            titleLabel.text = title
            titleContainer.addSubview(titleLabel)
            addSubview(titleContainer)
            titleLabel.snp.makeConstraints { make in
                make.edges.equalToSuperview().inset(style.titleContentInset)
            }
            titleContainer.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalToSuperview()
                make.right.equalToSuperview()
            }
            lastView = titleContainer
        }
        
        // 2. 添加文本
        if let message = style.message, !message.isEmpty {
            messageLabel.font = style.messageFont
            messageLabel.numberOfLines = style.messageNumberOfLines
            messageLabel.text = message
            contentView.addSubview(messageLabel)
            addSubview(contentView)
            
            if let last = lastView {
                messageLabel.snp.makeConstraints { make in
                    let inset = UIEdgeInsets(top: 0,
                                             left: style.messageContentInset.left,
                                             bottom: style.messageContentInset.bottom,
                                             right: style.messageContentInset.right)
                    make.edges.equalToSuperview().inset(inset)
                }
                contentView.snp.makeConstraints { make in
                    make.top.equalTo(last.snp.bottom)
                    make.left.equalToSuperview()
                    make.right.equalToSuperview()
                }
            }else {
                messageLabel.snp.makeConstraints { make in
                    make.edges.equalToSuperview().inset(style.messageContentInset)
                }
                contentView.snp.makeConstraints { make in
                    make.top.equalToSuperview()
                    make.left.equalToSuperview()
                    make.right.equalToSuperview()
                }
            }
            lastView = contentView
        }
        // 3.判断是否有意义：没有标题，没有文本，直接return
        guard let last = lastView else { return }
        
        // 4. 添加底部按钮
        okBtn.titleLabel?.font = style.buttonFont
        okBtn.setTitleColor(style.okBtnColor, for: .normal)
        okBtn.setTitle(style.okBtnTitle, for: .normal)
        
        if style.isDoubleBtn {
            cancelBtn.titleLabel?.font = style.buttonFont
            cancelBtn.setTitleColor(style.cancelBtnColor, for: .normal)
            cancelBtn.setTitle(style.cancelBtnTitle, for: .normal)
            
            addSubview(cancelBtn)
            addSubview(okBtn)
            cancelBtn.snp.makeConstraints { make in
                make.top.equalTo(last.snp.bottom).offset(0.5)
                make.bottom.equalToSuperview()
                make.height.equalTo(style.buttonHeight)
                if style.isCancelRight {
                    make.right.equalToSuperview()
                }else {
                    make.left.equalToSuperview()
                }
            }
            okBtn.snp.makeConstraints { make in
                make.centerY.size.equalTo(cancelBtn)
                if style.isCancelRight {
                    make.right.equalTo(cancelBtn.snp.left).offset(-0.5)
                    make.left.equalToSuperview()
                }else {
                    make.left.equalTo(cancelBtn.snp.right).offset(0.5)
                    make.right.equalToSuperview()
                }
            }
        }else {
            addSubview(okBtn)
            okBtn.snp.makeConstraints { make in
                make.top.equalTo(last.snp.bottom).offset(0.5)
                make.height.equalTo(style.buttonHeight)
                make.left.right.bottom.equalToSuperview()
            }
        }
    }
    
    @objc private func cancelBtnAction(sender: UIButton) {
        btnActionHandle?(false)
    }
    
    @objc private func okBtnAction(sender: UIButton) {
        if style.isDoubleBtn {
            btnActionHandle?(true)
        }else {
            btnActionHandle?(false)
        }
    }
}
